//index.js
//获取应用实例
const app = getApp()
const util = require('../../utils/util.js');
const AccountTask = require('../../service/AccountTask.js');

var index = 0;
var that;
Page({
  data: {
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    duration:'300',
    scrollLeft:0,
    menuTop:0,
    menuFixed:false,
    winHeight:'',
    nickName: '',
    avatarUrl: '/images/default_avart.png',
    pageCount: 10,
    classes: ["全部", "家具", "书桌", "电脑耗材", "音响设备", "好友推荐"],
    currentTab: 0, // 导航栏切换索引
    //卡片数据
    cards: [
      ],
  },

  getUserInfo: function (e) {
    if (e.detail.userInfo) {
      app.globalData.userInfo = e.detail.userInfo
      this.setData({
        userInfo: e.detail.userInfo,
        hasUserInfo: true
      })
      //授权成功然后进行微信运动步数的授权
      var that = this;
      if (wx.canIUse('authorize')) {
        wx.authorize({
          scope: 'scope.werun',
          success() {
            //用户已经同意小程序使用微信运动步数数据
            that.setData({
              hasWerunData: true
            })
          },
          complete() {
            loginToService(this);
          }
        })
      } else {
        console.log("无法授权");
        //直接登录
        loginToService(this);
      }
    } else {
      console.log('授权失败！');
      wx.hideLoading();
    }
  },
  onLoad: function () {
    that = this

/**
 * test imgtoken
 */


        //-------------------登陆逻辑判断start---------------------------------------------------
/**
 * todo 
 * 判断是否有
 * 
 */
    //判断登陆任务
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo,
        hasUserInfo: true
      });
      loginToService(this);
    } else if (this.data.canIUse) {
      // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userInfoReadyCallback = res => {
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        });
        /**
         * 本地存储取token 给 app.globalData.token
         * 如果token存在，加载数据  否则  走wx.login
         */
        app.globalData.token = wx.getStorageSync("token");
        if (app.globalData.token){
          this.loadMainData();
       }else{
         loginToService(this);
       } 
      }
    } else {
      // 在没有 open-type=getUserInfo 版本的兼容处理
      wx.getUserInfo({
        success: res => {
          app.globalData.userInfo = res.userInfo
          this.setData({
            userInfo: res.userInfo,
            hasUserInfo: true
          })
        }
      })
    }
    //-------------------登陆逻辑判断 end------------------------------------------------------------------

    function loginToService(e) {
      // 登录：首先调用wx登录接口拿到code
      wx.login({
        success: res => {
          // 存储code，以便其他接口使用
          app.globalData.wxUserCode = res.code;
          try {
            var that = e;
            var params = {
              'code': app.globalData.wxUserCode,
            };
            wx.showLoading({
              title: '加载中',
            });
            console.log("开始load");
            AccountTask.getToken(params, function (data) {
              wx.hideLoading();
              console.log("succ-load:"+data.errno);
              if (data.code === 10000) {
                app.globalData.token = data.data.token;
                that.loadMainData(); 
                try {
                wx.setStorageSync('token', data.data.token);
                } catch (e) {
                  console.log('微信存储数据出错！不影响');
                }
                //直接进主页 todo
              } else {
                util.errorCodeToast(data);
              }
              console.log("succ---->")
            }, function () {
              console.log("fail---->")
              wx.hideLoading();
              wx.showModal({
                title: '提示',
                showCancel: false,
                confirmText: '知道了',
                content: '登录失败！'
              });
            });
            // }
          } catch (e) {
            wx.showModal({
              title: '提示',
              showCancel: false,
              confirmText: '知道了',
              content: '获取数据失败，请稍后重试！'
            });
          }
        },
        fail: res => {
          wx.showModal({
            title: '提示',
            showCancel: false,
            confirmText: '知道了',
            content: '登录失败，请稍后重试！'
          });
        }
      })
    }
    //  高度自适应
    wx.getSystemInfo({
      success: function (res) {
        var clientHeight = res.windowHeight,
          clientWidth = res.windowWidth,
          rpxR = 750 / clientWidth;
        var calc = clientHeight * rpxR - 200;
        that.setData({
          winHeight: calc
        });
      }
    });
  },

  clickStar: function (e) {
    that = this
    var index = e.currentTarget.dataset.index
    var cards = that.data.cards
    var star = "cards["+index +"].onStar"
    this.setData({
      [star]: !cards[index].onStar
    })
  },

  //点击了页面
  clickCell: function (e) {
    
  },
  deleteCell:function(e){
    var id =1;
   id = e.currentTarget.dataset.index
    AccountTask.deleteProduct({"productionId":id},function(res){
       that.loadMainData();
    });

  },
  //点击进入二维码界面
  clickSearchCode: function () {
    wx.scanCode({
      onlyFromCamera: false,
      scanType: ["qrCode"],
      success: function (res) {
        console.log(res)
        wx.showModal({
          title: res.result,
          content: '这是一个窗口',
          showCancel: true,
          cancelText: '',
          cancelColor: '',
          confirmText: '确认',
          confirmColor: '#999999',
          success: function (res) {
            if (res.confirm) {

            }
          },
          fail: function (res) { },
          complete: function (res) { },
        })
      },
      fail: function (res) { },
    })
  },

  pageChange: function (e) {
    that = this;
    var current = e.detail.current;
    that.setData({
      currentTab:current
    })
    this.scrollToCenter(current)
  },

  //点击了页面header选项
  clickHeaderClass: function (ev) {
    that = this
    //设置滑动时间
    that.setData({
      duration:'0'
    })
    var scal = app.globalData.pxScal
    var index = ev.currentTarget.dataset.index;
    that.setData({ currentTab: index });
    this.scrollToCenter(index,function(){
      that.setData({
        duration: '300'
      })
    })
  },


  //滑动title显示到中间
  scrollToCenter: function (index,fn) {
    var obj = wx.createSelectorQuery();
    obj.selectAll('#_title').boundingClientRect(function (rect) {}).select('#affix').fields({
      scrollOffset: true,
    }, function (res) {})
    obj.exec(function (res) {
      var rectW = res[0][index].width
      var rectLeft = res[0][index].left
      var scrollLeft = res[1].scrollLeft
      var offsetLeft = rectLeft + scrollLeft

      //当前中点离中线多远
      var scrollY = (offsetLeft + rectW / 2 - 375 / 2)
      that.setData({
        scrollLeft: scrollY
      })
      
      if(fn){
        fn()
      }
    });
  },

  scrollTop: function (e) {
    that = this
    that.data.scrollLeft = e.detail.scrollLeft
  },

  //跳到商品详情
  showGoodsDetails: function (e) {
    var productionId = e.currentTarget.dataset.index
    app.globalData.productionId = productionId;
    wx.navigateTo({
      url: '../detailsPage/detailsPage',
    })
  },
  //跳转到我的备注
  clickToRemark: function () {
    wx.navigateTo({
      url: '../myRemark/myRemark',
    })
  },
  loadMainData: function () {//加载主要信息
    //todo
    AccountTask.getImgToken({}, function () { }, function () { })
    // AccountTask.getToken(params, function (data) 
    AccountTask.getCollectionsByType({},function(data){
      var tempClasses=[];
      for(var i=0;i<data.data.length;i++){
        console.log(i + "---" + data.data[i].typeName + "-----" + data.data[i].goods.length);

        tempClasses.push(data.data[i].typeName);
      }
      // this.data.classes=tempClasses;
      // this.data.tempCards=tempCards;
      that.setData({
        classes: tempClasses,
        cards: data.data
          });
    },function(){

    }) 
  },
  
})


